package com.shaoshaohuo.app.ui.ec;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.DumpGoodsGridAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.ListViewAction;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.EcCategorySecond;
import com.shaoshaohuo.app.entity.EcCategoryThird;
import com.shaoshaohuo.app.entity.SupplyRecord;
import com.shaoshaohuo.app.entity.SupplyRecordEntity;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.net.HttpRequest;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.utils.ViewUtil;
import com.shaoshaohuo.app.utils.city.Cityinfo;
import com.shaoshaohuo.app.view.SelectProductTypePop;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.XListView;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.entity.Area;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenu;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuCreator;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuItem;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * 品牌直营商品列表
 * Created by osborn on 16/7/5.
 */
public class BrandScopeActivity extends BaseActivity implements View.OnClickListener, XListView.IXListViewListener {
    private static final int SELECT_PRODUCT_TYPE = 1;
    private static final int SELECT_MARKET_CITY = SELECT_PRODUCT_TYPE + 1;

    private TopbarView mTopbarView;

    private TextView mLeftTabText;
    private TextView mCenterTabText;
    private TextView mRightTabText;

    private PullToRefreshGridView mPullRefreshGridView;
    private GridView mGridView;
    private DumpGoodsGridAdapter<SupplyRecord> mAdapter;

    private List<SupplyRecord> mDataList = new ArrayList<SupplyRecord>();
    private String bigpid = "";
    private String pid = "";
    private String catid = "";
    private CascadingMenuPopWindow cascadingMenuPopWindow;
    private String cityid = "";

    private String action = ListViewAction.NEW2;
    private String cursor = "0";
    private int offset = 10;
    private String shuai = "0";

    private EcCategorySecond ecCategorySecond;
    private Cityinfo selectCity; // 选中的市
    protected List<EcCategoryThird> mVarietyList;
    private SelectProductTypePop selectProductTypePop;
    private ImageView ivIconHand;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(new TopbarView(this));
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                setContentView(R.layout.activity_brand_scope);
                initData();
                initView();
                setUpView();
//                addShade();
                requestData(true);
            }
        }, 200);
    }
    /**
     * 添加遮罩
     */
    private void addShade() {
        if (StringUtil.isEmpty(SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.SHADE_SUPPLY_HALL, ""))) {
            final RelativeLayout markLayout = (RelativeLayout) findViewById(R.id.layout_mark);
            markLayout.setVisibility(View.VISIBLE);
            ivIconHand = (ImageView) findViewById(R.id.icon_hand);
            TranslateAnimation myAnimation_Translate = new TranslateAnimation(ViewUtil.dip2px(this, 220f), ViewUtil.dip2px(this, 113f), 0f, 0f);
            myAnimation_Translate.setDuration(3000);
            myAnimation_Translate.setRepeatCount(Integer.MAX_VALUE);
            ivIconHand.startAnimation(myAnimation_Translate);
            markLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    markLayout.setVisibility(View.GONE);
                    SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.SHADE_SUPPLY_HALL, "true");
                }
            });
        }
    }
    protected void initData() {

    }

    private void initView() {
        mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

        mLeftTabText = (TextView) this.findViewById(R.id.textview_tab_left);
        mCenterTabText = (TextView) this.findViewById(R.id.textview_tab_center);
        mRightTabText = (TextView) this.findViewById(R.id.textview_tab_right);

        mPullRefreshGridView = (PullToRefreshGridView) this.findViewById(R.id.gridview_data_list);
        mGridView = mPullRefreshGridView.getRefreshableView();
        /*mPullRefreshGridView.setMenuCreator(new MySwipeMenuCreator());
        mPullRefreshGridView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                SupplyRecord record = mDataList.get(position);
                if (AccountManager.getUserId().equals(record.getUserid())) {
                    return false;
                }
                switch (index) {
                    case 0:
                        IMFactory.openChat(BrandScopeActivity.this, record.getUserid());
                        break;
                    case 1:
                        DeviceHelper.callPhone(BrandScopeActivity.this, record.getMobile(), record.getKey());
                        break;
                }
                return false;
            }
        });*/
    }

    private void setUpView() {
        mTopbarView.setCenterText("妈妈爱果品牌直供");
        mTopbarView.setLeftView(true, true);

        mLeftTabText.setOnClickListener(this);
        mCenterTabText.setOnClickListener(this);
        mRightTabText.setOnClickListener(this);


        setGridView();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textview_tab_left:
                selectProduct();
                break;
            case R.id.textview_tab_center:
                if (mVarietyList == null || mVarietyList.isEmpty()) {
                    if (mLeftTabText.getText().toString().equals("分类") || mLeftTabText.getText().toString().equals("不限")) {
                        showToast("请选择分类");
                    } else {
                        showToast("当前分类未细分品种");
                    }
                    return;
                }
                if (selectProductTypePop == null) {

                    selectProductTypePop = new SelectProductTypePop(this);
                    selectProductTypePop.setOnSelectItemListener(new SelectProductTypePop.OnSelectItemListener() {

                        @Override
                        public void onSelect(List<EcCategoryThird> list) {
                            StringBuilder sb = new StringBuilder();
                            for (EcCategoryThird item : list) {
//                                sb.append(item.getCatid() + ",");
                            }
                            catid = sb.toString();
                            refrensh();
                        }
                    });
                }
                selectProductTypePop.setData(mVarietyList);
                selectProductTypePop.showLocation(mLeftTabText);
                break;
            case R.id.textview_tab_right:
                selectMarketCity();
                break;
        }
    }

    private void selectMarketCity() {
//		new CascadingMenuPopWindow().showInstance(this, mRightTabText, new NMCascadingMenuViewOnSelectListener());
        if (cascadingMenuPopWindow == null) {
            //向三级menu添加地区数据
            cascadingMenuPopWindow = new CascadingMenuPopWindow(this);
            cascadingMenuPopWindow
                    .setMenuViewOnSelectListener(new NMCascadingMenuViewOnSelectListener());
            cascadingMenuPopWindow.showAsDropDown(mRightTabText, 5, 5);
        } else if (cascadingMenuPopWindow != null
                && cascadingMenuPopWindow.isShowing()) {
            cascadingMenuPopWindow.dismiss();
        } else {
            cascadingMenuPopWindow.showAsDropDown(mRightTabText, 5, 5);
        }
    }

    class NMCascadingMenuViewOnSelectListener implements
            CascadingMenuViewOnSelectListener {

        @Override
        public void getValue(Area city, String fullname) {
//            mRightTabText.setText(city.getName());
//            selectCity = CityinfoUtil.convert(city);
            refrensh();
        }

    }
    private void selectProduct() {
        Intent intent = new Intent(this, ProductTypeActivity.class);
        startActivityForResult(intent, SELECT_PRODUCT_TYPE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SELECT_PRODUCT_TYPE:
                    EcCategorySecond second = (EcCategorySecond) data.getSerializableExtra(ExtraName.ecCategorySecond);
//                    if (ecCategorySecond != null && !TextUtils.isEmpty(ecCategorySecond.getCatid())
//                            && ecCategorySecond.getCatid().equals(second.getCatid())) {
//                    } else {
//
//                        if (ecCategorySecond != null && second.getCatname().equals("不限")
//                                && ecCategorySecond.getCatname().equals("不限")) {
//                            return;
//                        }
//                        ecCategorySecond = second;
//                        bigpid = ecCategorySecond.getBigpid();
//                        pid = ecCategorySecond.getCatid();
//                        mLeftTabText.setText(ecCategorySecond.getCatname());
//                        mVarietyList = null;
//                        refrensh();
//                        catid = "";
//                        if (!ecCategorySecond.getCatname().equals("不限")) {
//                            getVariety(ecCategorySecond);
//                        }
//                    }
                    break;
                case SELECT_MARKET_CITY:
				/*selectProvince = (Province) Data.getSerializableExtra(ExtraName.province);
				selectCity = (City) Data.getSerializableExtra(ExtraName.city);
				mRightTabText.setText(selectCity.getCityname());*/
                    refrensh();
                    break;
            }
        }
    }

    private void getVariety(EcCategorySecond item) {
        startLoadingDialog();
//        RequestService.getInstance().getEcCategoryVariety(this, item.getBigpid(), item.getCatid(), EcVarietyEntity.class,
//                new HttpRequest.RequestListener() {
//
//                    @Override
//                    public void onSuccess(int requestCode, BaseEntity resultData) {
//                        dismissLoadingDialog();
//                        if (resultData.isOk()) {
//                            EcVarietyEntity entity = (EcVarietyEntity) resultData;
//                            // setVarietyAdapter(entity.getData().getList());
//                            mVarietyList = entity.getData().getList();
//                        } else {
//                            showToast(resultData.getMsg());
//                        }
//                    }
//
//                    @Override
//                    public void onFailed(int requestCode, Exception error, String msg) {
//                        dismissLoadingDialog();
//                        showToast(R.string.please_check_network);
//                    }
//                });
    }

    private void refrensh() {
        mDataList.clear();
        onRefresh();
    }

    private void requestData(boolean isLoading) {
        if (isLoading) {
            startLoadingDialog();
        }
        if (selectCity != null) {
            cityid = selectCity.getId();
        } else {
            cityid = null;
        }

        // RequestService.getInstance().supplyPublishList(this, "",
        // "","","","","","","", SupplyRecordEntity.class,
        RequestService.getInstance().supplyPublishList(this, cursor, offset + "", action, bigpid, pid, catid, cityid,
                shuai, "brandScope", SupplyRecordEntity.class, new HttpRequest.RequestListener() {

                    @Override
                    public void onSuccess(int requestCode, BaseEntity resultData) {
                        dismissLoadingDialog();
                        if (resultData.isOk()) {
                            SupplyRecordEntity entity = (SupplyRecordEntity) resultData;
                            List<SupplyRecord> list = entity.getData().getList();
                            mDataList.addAll(list);

                            if ((mDataList.size() < offset) || (action.equals(ListViewAction.HISTORY2) && list.size() < offset)) {
                                // mPullRefreshGridView.setPullLoadEnable(false);
//                                mPullRefreshGridView.endLoadingMore("没有更多了");
                            }
                            setAdapter(mDataList);

                        } else {
                            showToast(resultData.getMsg());
                        }
                        onLoad();
                    }

                    @Override
                    public void onFailed(int requestCode, Exception error, String msg) {
                        dismissLoadingDialog();
                        showToast(msg);
                        onLoad();
                    }
                });
    }

    protected void setAdapter(List<SupplyRecord> mDataList2) {
        // if(mDataList2.isEmpty()){
        // mDataList2.add(new SupplyRecord());
        // mDataList2.add(new SupplyRecord());
        // mDataList2.add(new SupplyRecord());
        // mDataList2.add(new SupplyRecord());
        // mDataList2.add(new SupplyRecord());
        // mDataList2.add(new SupplyRecord());
        // mDataList2.add(new SupplyRecord());
        // mDataList2.add(new SupplyRecord());
        // mDataList2.add(new SupplyRecord());
        // mDataList2.add(new SupplyRecord());
        // }
        if (mAdapter == null) {
            mAdapter = new DumpGoodsGridAdapter<SupplyRecord>(this, mDataList2, false);
            mPullRefreshGridView.setAdapter(mAdapter);
        } else {
            mAdapter.setData(mDataList2);
        }
    }

    private void setGridView() {
//        mPullRefreshGridView.setPullLoadEnable(true);
//        mPullRefreshGridView.setPullRefreshEnable(true);
//        mPullRefreshGridView.setXListViewListener(this);
        /*TextView tv = new TextView(this);
        tv.setGravity(Gravity.CENTER);
        tv.setText("Empty View, Pull Down/Up to Add Items");
        mPullRefreshGridView.setEmptyView(tv);*/
        initIndicator();
        mPullRefreshGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
                onRefresh();
                new GetDataTask().execute();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {
                onLoadMore();
                new GetDataTask().execute();
            }
        });

        mPullRefreshGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // PurchaseRecord order = (Order)
                // parent.getItemAtPosition(position);
                // Intent intent = new
                // Intent(PurchaseRecordActivity.this,OrderDetailShipperActivity.class);
                // intent.putExtra(ExtraName.orderid, order.getBusinessorderid());
                // startActivity(intent);
                SupplyRecord supply = (SupplyRecord) parent.getItemAtPosition(position);
                Intent intent = new Intent(BrandScopeActivity.this, SupplyDetailActivity.class);
                intent.putExtra(ExtraName.id, supply.getId());
                intent.putExtra(SupplyDetailActivity.EXTRA_IS_FROM_BRAND_SCOPE, "true");
                startActivity(intent);
            }
        });
    }

    private void initIndicator()
    {
        ILoadingLayout startLabels = mPullRefreshGridView
                .getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("松开刷新数据");// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("正在加载...");// 刷新时
        startLabels.setReleaseLabel("松开刷新数据");// 下来达到一定距离时，显示的提示

        /*ILoadingLayout endLabels = mPullRefreshGridView.getLoadingLayoutProxy(
                false, true);
        endLabels.setPullLabel("你可劲拉，拉2...");// 刚下拉时，显示的提示
        endLabels.setRefreshingLabel("好嘞，正在刷新2...");// 刷新时
        endLabels.setReleaseLabel("你敢放，我就敢刷新2...");// 下来达到一定距离时，显示的提示*/
    }

    @Override
    public void onRefresh() {
//		if (mDataList.size() > 0) {
//			cursor = mDataList.get(0).getCursor();
//		} else {
        cursor = "0";
//		}
        mDataList.clear();
        action = ListViewAction.NEW2;
//        mPullRefreshGridView.setPullLoadEnable(true);
        requestData(false);
    }

    @Override
    public void onLoadMore() {
        if (mDataList.size() > 0) {
            cursor = mDataList.get(mDataList.size() - 1).getCursor();
        } else {
            cursor = "0";
        }
        action = ListViewAction.HISTORY2;
        requestData(false);
    }

    private void onLoad() {
//        mPullRefreshGridView.stopRefresh();
//        mPullRefreshGridView.stopLoadMore();
    }

    @Override
    protected void onDestroy() {
        if (cascadingMenuPopWindow != null) {
            cascadingMenuPopWindow.dismiss();
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    class MySwipeMenuCreator implements SwipeMenuCreator {
        @Override
        public void create(SwipeMenu menu) {
            SwipeMenuItem imMenu = new SwipeMenuItem(BrandScopeActivity.this);
            imMenu.setBackground(new ColorDrawable(Color.parseColor("#2eabf1")));
            imMenu.setIcon(R.drawable.icon_chat_left_ad);
            imMenu.setWidth(StringHelper.dip2px(BrandScopeActivity.this, 70));
            menu.addMenuItem(imMenu);
            SwipeMenuItem callMenu = new SwipeMenuItem(BrandScopeActivity.this);
            callMenu.setBackground(new ColorDrawable(Color.parseColor("#6dc114")));
            callMenu.setIcon(R.drawable.icon_tel_left_ad);
            callMenu.setWidth(StringHelper.dip2px(BrandScopeActivity.this, 70));
            menu.addMenuItem(callMenu);
        }
    }

    private class GetDataTask extends AsyncTask<Void, Void, String[]> {
        @Override
        protected String[] doInBackground(Void... voids) {
            return new String[0];
        }

        @Override
        protected void onPostExecute(String[] result) {
            // Call onRefreshComplete when the list has been refreshed.
            mPullRefreshGridView.onRefreshComplete();
            super.onPostExecute(result);
        }
    }
}
